package utillinkhandler

import (
	"gioui.org/app"
	"gioui.org/x/markdown"
	"gioui.org/x/richtext"
	"github.com/inkeliz/giohyperlink"
	"log"
	"net/url"
)

// Handles link events by default opening all normally parsed links via
// giohyperlink. If a URI has the transito:// scheme then the body/host of
// the link will be return; otherwise empty string returned
func HandleLinkEvents(window *app.Window, textstate *richtext.InteractiveText) string {
	giohyperlink.InsecureIgnoreScheme = true

	for o, events := textstate.Events(); o != nil; o, events = textstate.Events() {
		for _, e := range events {
			switch e.Type {
			case richtext.Click:
				if urlLink, ok := o.Get(markdown.MetadataURL).(string); ok && urlLink != "" {

					if u, err := url.Parse(urlLink); err != nil {
						log.Printf("Error parsing link <%s>: %v", urlLink, err)
					} else if u.Scheme == "transito" {
						return u.Host
					} else if err := giohyperlink.Open(urlLink); err != nil {
						log.Printf("Error opening link <%s>: %v", urlLink, err)
					}
				}
			case richtext.Hover:
			case richtext.LongPress:
				if urlLink, ok := o.Get(markdown.MetadataURL).(string); ok && urlLink != "" {
					window.Option(app.Title(urlLink))
				}
			}
		}
	}
	return ""
}
